package com.yksj.healthtalk.ui.server;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 服务中心主页
 * @author zhao
 *
 */
public class ServerCenterHomeFragment extends Fragment {
	
	FragmentTabHost mFragmentTabHost;
	String id;//用户id
	private String title;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		id = getArguments().getString("id");
		title = getArguments().getString("title");
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.server_center_home_layout,null);
		mFragmentTabHost = (FragmentTabHost)view.findViewById(android.R.id.tabhost);
		mFragmentTabHost.setup(getActivity(), getFragmentManager(), R.id.realtabcontent);
		id = getArguments().getString("id");
		title = getArguments().getString("title");
		addTabSpec(inflater);
		return view;
	}

	private void addTabSpec(LayoutInflater inflater){
		TabSpec tabSpec = mFragmentTabHost.newTabSpec("introduce");//主页介绍
		tabSpec.setIndicator(getString(R.string.walk_in_me));
		View view = inflater.inflate(R.layout.tab_txt_layout, null);
		TextView textView = (TextView)view.findViewById(R.id.tab_lable);
		tabSpec.setIndicator(view);
		textView.setText(getString(R.string.walk_in_me));
		Bundle bundle = new Bundle();
		bundle.putString("id",id);
		bundle.putString("title", title);
		mFragmentTabHost.addTab(tabSpec,ServerCenterIntroduceFragment.class,bundle);
		
		
		tabSpec = mFragmentTabHost.newTabSpec("news");//新闻发布
		tabSpec.setIndicator(getString(R.string.info_publish));
		view = inflater.inflate(R.layout.tab_txt_layout, null);
		textView = (TextView)view.findViewById(R.id.tab_lable);
		tabSpec.setIndicator(view);
		textView.setText(getString(R.string.info_publish));
		bundle = new Bundle();
		bundle.putString("id",id);
		bundle.putString("type","2");
		mFragmentTabHost.addTab(tabSpec,ArrayListFragment.class,bundle);
		
		
		tabSpec = mFragmentTabHost.newTabSpec("activites");//活动参与
		tabSpec.setIndicator(getString(R.string.exercise_join));
		view = inflater.inflate(R.layout.tab_txt_layout, null);
		textView = (TextView)view.findViewById(R.id.tab_lable);
		tabSpec.setIndicator(view);
		textView.setText(getString(R.string.exercise_join));
		bundle = new Bundle();
		bundle.putString("id",id);
		bundle.putString("type","1");
		mFragmentTabHost.addTab(tabSpec,ArrayListFragment.class,bundle);
	}
	
	
	/**
	 * 新闻和活动
	 * @author zhao
	 */
	public static class ArrayListFragment extends ListFragment implements OnRefreshListener<ListView>{
		private String id;
		private String type;
		private ArratListAdapter mAdapter;
		private PullToRefreshListView mPullToRefreshListView;
		private static int pageNum=1;
		List<JSONObject> list = new ArrayList<JSONObject>();
		
		final JsonHttpResponseHandler mResponseHandler = new JsonHttpResponseHandler(){
			public void onSuccess(int statusCode, org.json.JSONArray response) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
				if(statusCode == 200 && response != null &&response.length()>0){
					list.clear();
					for (int i = 0; i < response.length(); i++) {
						try {
							JSONObject jsonObject = response.getJSONObject(i);
							String time = jsonObject.getString("PROMULGATE_TIME");
							try {
								Date date = dateFormat1.parse(time);
								String timeStr = dateFormat.format(date);
								jsonObject.put("PROMULGATE_TIME", timeStr);
							} catch (ParseException e) {
								e.printStackTrace();
							}
							list.add(jsonObject);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					mAdapter.onDataChange(list);
					pageNum++;
				}
				
				if(pageNum==1){
					if(list.size()==0){
						ToastUtil.showToastPanl("暂无内容...");
						return;
					}
				}
			};
			public void onFinish() {
				mPullToRefreshListView.onRefreshComplete();
			};
			
		};
		private ListView mListView;
		
		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			id = getArguments().getString("id");
			type = getArguments().getString("type");
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.server_center_home_list_layout,null);
			mPullToRefreshListView = (PullToRefreshListView)view.findViewById(R.id.hall);
			mListView = mPullToRefreshListView.getRefreshableView();
			mPullToRefreshListView.setOnRefreshListener(this);
			return view;
		}
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			mAdapter = new ArratListAdapter(getLayoutInflater(savedInstanceState));
			mListView.setAdapter(mAdapter);
			pageNum=1;
			HttpRestClient.doHttpQueryServerCenterNewsOrActivite(id,type,"1",mResponseHandler,String.valueOf(pageNum),"10");
		}
		
		@Override
		public void onListItemClick(ListView l, View v, int position, long id) {
			super.onListItemClick(l, v, position, id);
			JSONObject jsonObject = mAdapter.getItem(position-1);
			try {
				String newId = mAdapter.getID(jsonObject);
				Intent intent = new Intent(getActivity(),ServerCenterContentActivity.class);
				intent.putExtra("newsId", newId);
				intent.putExtra("type", type);
				intent.putExtra("content",jsonObject.toString());
				startActivity(intent);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onRefresh(PullToRefreshBase<ListView> refreshView) {
			HttpRestClient.doHttpQueryServerCenterNewsOrActivite(id,type,"1",mResponseHandler,String.valueOf(pageNum),"10");
		}
	}
	
	static class ArratListAdapter extends BaseAdapter{
		final List<JSONObject> mList = new ArrayList<JSONObject>();
		final LayoutInflater mInflater;
		
		public ArratListAdapter(LayoutInflater inflater) {
			this.mInflater = inflater;
		}
		
		public void onDataChange(List<JSONObject> list){
			mList.addAll(list);
			this.notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mList.size();
		}

		@Override
		public JSONObject getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		public String getName(JSONObject jsonObject) throws JSONException{
			return jsonObject.getString("NEWS_TITLE");
		}
		
		public String getTime(JSONObject jsonObject) throws JSONException{
			return jsonObject.getString("PROMULGATE_TIME");
		}

		public String getID(JSONObject jsonObject) throws JSONException{
			return jsonObject.getString("NEWS_ID");
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder viewHolder;
			
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.news_item, null);
				TextView titleTextView = (TextView) convertView
						.findViewById(R.id.new_title);
				TextView timeTextView = (TextView) convertView
						.findViewById(R.id.new_time);
				convertView.setTag(viewHolder);
				viewHolder.timeTextV = timeTextView;
				viewHolder.titleTextV = titleTextView;
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			
			JSONObject jsonObject = getItem(position);
			String name = null;
			String time = null;
			try {
				name = getName(jsonObject);
				time = getTime(jsonObject);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			viewHolder.timeTextV.setText(time);
			viewHolder.titleTextV.setText(name);
			return convertView;
		}
	}
	
	private static class ViewHolder {
		TextView timeTextV;
		TextView titleTextV;
	}
	
}
